import { Dropdown, Layout, Menu } from '@arco-design/web-react';
import { Outlet, useLocation, useNavigate } from 'react-router-dom';
import { MenuTypes } from './mainNavBar';
import { useEffect, useRef, useState } from 'react';
import { AppStore } from '@src/types';
import { useDispatch, useSelector } from 'react-redux';
import main from '@src/main';
import { confirmDialog } from './dialog';
import { logoutRequest } from '@src/redux/logoutReducer';
import { IconClose, IconDown } from '@arco-design/web-react/icon';
import { SVGIcon } from './svg/svgIcon';
interface Props {
  menus: MenuTypes[];
}
export default function Layout1({ menus }: Props) {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const location = useLocation();
  const menuMapRef = useRef<{ [x: string]: MenuTypes }>({});
  const [selectKey, setSelectKey] = useState('');
  const user = useSelector((state: AppStore) => state.user);
  const [watermark, setWatermark] = useState(main.watermark);

  // 点击过的历史记录
  const [historyList, setHistoryList] = useState<MenuTypes[]>([]);
  // 用户下拉菜单内容
  const dropdownItems = (
    <Menu>
      <Menu.Item key="1" onClick={handleToAccount}>
        个人中心
      </Menu.Item>
      <Menu.Item key="2" onClick={handleWatermark}>
        {watermark ? '关闭水印' : '开启水印'}
      </Menu.Item>
      <Menu.Item key="99" onClick={handleLogout}>
        退出登录
      </Menu.Item>
    </Menu>
  );

  function handleWatermark() {
    let show = !watermark;
    setWatermark(show);
    main.createWatermark(show);
  }

  function handleToAccount() {
    setSelectKey('');
    navigate('/account');
  }

  // 用户信息下拉菜单点击
  async function handleLogout() {
    let modalRes = await confirmDialog({ content: '确定要退出登录吗?' });
    if (modalRes !== 1) return;

    setSelectKey('');
    dispatch(logoutRequest());
    navigate('/login', { replace: true });
  }

  useEffect(() => {
    let map: { [x: string]: MenuTypes } = {};
    for (let m of menus) {
      map[m.key] = Object.assign({}, m, { parent: null });
      if (m.subs?.length) {
        for (let s of m.subs) {
          if (!s.path.endsWith('detail/:id')) {
            map[m.key + s.key] = Object.assign({}, s, { parent: m.key });
          }
        }
      }
    }
    menuMapRef.current = map;
  }, [menus]); // eslint-disable-line

  useEffect(() => {
    // 每次路由变化都重新确认要选中的一级菜单和二级菜单
    let pathname = location.pathname;
    let keys = Object.keys(menuMapRef.current);
    for (let k of keys) {
      // 查询所有菜单
      let menu = menuMapRef.current[k];
      if (menu) {
        // 如果路由地址和当前菜单的路由一致，直接选中当前的菜单
        if (pathname.toLowerCase() === (menu.link ?? '').toLowerCase() || pathname === `${menu.link}/`.toLowerCase()) {
          // 如果没有parent，说明当前是一级菜单，选中自己的第一项,没有子级就选中自己
          if (!menu.parent && menu.subs?.length) {
            setSelectKey(menu.subs[0].key);
            calcHistory(menu.subs[0], true);
          } else {
            // 有parent 说明当前是二级菜单，选中自己
            setSelectKey(menu.key);
            calcHistory(menu, true);
          }
          break;
        } else if (menu.links) {
          // 如果不一致，则判断关联的菜单
          let has = false;
          for (let l of menu.links) {
            // 如果当前路由是以关联菜单开头或包含关联菜单，也选中当前菜单
            if (
              pathname.toLowerCase().startsWith(l.toLowerCase()) ||
              pathname.toLowerCase().includes(l.toLowerCase())
            ) {
              has = true;
              if (!menu.parent && menu.subs?.length) {
                setSelectKey(menu.subs[0].key);
                calcHistory(menu.subs[0], true);
              } else {
                // 有parent 说明当前是二级菜单，选中自己
                setSelectKey(menu.key);
                calcHistory(menu, true);
              }

              break;
            }
          }
          if (has) {
            break;
          }
        }
      }
    }
  }, [location, menus]); //eslint-disable-line

  function createMenuItem(menu: MenuTypes) {
    if (menu.subs?.length) {
      let showSubs: Array<MenuTypes> = [];
      menu.subs!.forEach((sub) => {
        if (!sub.path.endsWith('detail/:id')) {
          showSubs.push(sub);
        }
      });
      return (
        <Menu.SubMenu
          key={menu.key}
          title={
            <div className="d-flex-r ai-center">
              {!!menu.icon && <SVGIcon type={menu.icon} className="font-16 mr-5" />}
              {menu.label}
            </div>
          }
        >
          {showSubs.map((sub) => createMenuItem(sub))}
        </Menu.SubMenu>
      );
    }

    return (
      <Menu.Item key={menu.key} className="d-flex-r ai-center">
        {!!menu.icon && <SVGIcon type={menu.icon} className="font-16 mr-5" />}
        {menu.label}
      </Menu.Item>
    );
  }

  function onClickMenuItem(key: string, event: any, keyPath: string[]) {
    let menu = menuMapRef.current[keyPath.reverse().join('')];
    if (!menu) return;
    if (menu.link?.startsWith('http')) {
      window.open(menu.link, '_blank');
      return;
    }
    if (menu.subs?.length) return;
    if (menu.link) {
      calcHistory(menu, true);
      navigate(menu.link);
      setSelectKey(menu.key);
    }
  }

  function calcHistory(item: MenuTypes, plus: boolean) {
    let list = [];
    let has = false;
    historyList.forEach((i) => {
      if (item.key === i.key) {
        if (plus) {
          has = true;
          list.push(i);
        }
      } else {
        list.push(i);
      }
    });
    if (plus && !has) {
      list.push(item);
    }
    if (list.length > 10) {
      list = list.slice(-10);
    }
    setHistoryList(list);
  }

  function handleSubChange(item?: MenuTypes) {
    if (!item) {
      setSelectKey('');
      return;
    }
    if (item.path.startsWith('http')) {
      window.open(item.path, '_blank');
    } else if (item.link) {
      calcHistory(item, true);
      navigate(item.link);
      setSelectKey(item.key);
    }
  }
  return (
    <Layout className="layout-1">
      <Layout.Header className="layout-header">
        <div>Header</div>
        <div className="flex-1"></div>
        <Dropdown droplist={dropdownItems} position="br" trigger="click">
          <span
            className="d-flex-r ai-center ml-20 mr-20 text-second-color font-12 maxw-140 cursor-pointer"
            onClick={(e) => e.preventDefault()}
          >
            {user?.user?.userName ?? user?.user?.nickName}
            <IconDown />
          </span>
        </Dropdown>
      </Layout.Header>
      <Layout className="layout-content-block">
        <Layout.Sider>
          <Menu autoScrollIntoView accordion onClickMenuItem={onClickMenuItem} selectedKeys={[selectKey]}>
            {menus.map((menu) => createMenuItem(menu))}
          </Menu>
        </Layout.Sider>
        <Layout.Content className="layout-content">
          <div className="d-flex-r pt-10 pl-20 pb-20">
            {historyList.map((i) => (
              <div
                key={i.key}
                className={`d-flex-r ai-center mr-10 ${
                  selectKey === i.key ? 'text-primary-color' : 'text-second-color'
                }`}
              >
                <span className="cursor-pointer omit-text mr-10" onClick={() => handleSubChange(i)}>
                  {i.label}
                </span>
                <IconClose className="cursor-pointer" onClick={() => calcHistory(i, false)} />
                <div className="w-1 h-14 bg-9-color ml-10 mr-10" />
              </div>
            ))}
          </div>
          <Outlet />
        </Layout.Content>
      </Layout>
    </Layout>
  );
}
